import { useEffect, useRef, useState } from 'react';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Input, message, TableProps, Tabs, TabsProps } from 'antd';
import Modals from '@/components/modals/Modals';
import Tables from '@/components/tables/tables';
import appService from '@/api/services/appService';
import { GetReviewAppList, ReviewAppRes } from '@/common/types';
import { debounce } from 'lodash';
import { formatData } from '@/utils/time';
import useModal from '@/hooks/use-modal/useModal';
import { useNavigate } from 'react-router-dom';
import PagesHeader from '@/components/pages-header';
import './index.scss';
import { useSize } from 'ahooks';
import NotData from '@/components/NotData';
import { LONG_TEXT } from '@/common/app/constants';
import TextArea from '@/components/Antd/TextArea';
import { useParams } from '@/router/hooks';
import { SvgIcon } from '@/components/icon';
import TipDesc from '@/components/tipDesc/tipDesc';

const AppReview = () => {
  const navigate = useNavigate();

  const { key = '1' } = useParams() as {
    key: string;
  };

  const modal = useModal('dismiss', 'review', 'isVisible');

  const [tablesData, setTablesData] = useState<GetReviewAppList[]>([]);

  const [tipsValue, setTipsValue] = useState<ReviewAppRes>();

  const [dismiss, setDismiss] = useState('');

  const [tabsValue, setTabsValue] = useState(key);

  const [defaultDismiss, setDefaultDismiss] = useState<GetReviewAppList>();

  const [pagingInfo, setPagingInfo] = useState({
    page: 1,
    page_size: 10,
    searchText: '',
  });

  const [pagingTotal, setPagingTotal] = useState(0);

  // 添加行级展开状态管理
  const [expandedRows, setExpandedRows] = useState<Record<string, boolean>>({});

  // 切换行展开状态的函数
  const toggleRowExpansion = (appId: string) => {
    setExpandedRows((prev) => ({
      ...prev,
      [appId]: !prev[appId],
    }));
  };

  // 记录每行“审批意见”文本节点 ref 与溢出状态，用于展示“展开/收起”
  const contentRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const [overflowRowMap, setOverflowRowMap] = useState<Record<string, boolean>>({});

  // 监听容器尺寸变化，响应式时重新计算溢出
  const containerRef = useRef<HTMLDivElement>(null);
  const containerSize = useSize(containerRef);

  useEffect(() => {
    if (tabsValue === '1') {
      appService.getAppReviewList(pagingInfo).then((res) => {
        setTablesData(res.list);
        setPagingTotal(res.total);
        // 重置展开状态
        setExpandedRows({});
      });
    } else {
      appService.getAppReviewHistorList(pagingInfo).then((res) => {
        setTablesData(res.list);
        setPagingTotal(res.total);
        // 重置展开状态
        setExpandedRows({});
      });
    }
  }, [pagingInfo]);

  /**
   * @description: 切换Tabs
   * @param {string} key
   * @return {*}
   */
  const onChange = (key: string) => {
    setPagingInfo({
      page: 1,
      page_size: 10,
      searchText: '',
    });
    setTabsValue(key);
  };

  /**
   * @description: Tabs选项
   * @return {*}
   */
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: <div className="text-sm">待审批应用</div>,
    },
    {
      key: '2',
      label: <div className="text-sm">审批历史</div>,
    },
  ];

  const jumpOrchestration = (value: GetReviewAppList) => {
    if (value.app_type === 'agent') {
      navigate(
        `/apps/viewOrchestration?appType=${value.app_type}&appId=${value.app_id}&key=${tabsValue}`,
      );
    } else {
      navigate(
        `/apps/viewOrchestration?appType=${value.app_type}&appId=${value.app_id}&currentTab=preview&key=${tabsValue}`,
      );
    }
  };

  const getAppType = (value: string) => {
    switch (value) {
      case 'agent':
        return '智能体';
      case 'workflow':
        return '工作流';
      case 'plugin':
        return '插件';
      default:
        return value;
    }
  };

  /**
   * @description: TablesColumns
   * @return {*}
   */
  const columnsReview: TableProps<GetReviewAppList>['columns'] = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => (
        <div>
          <div className="text-[16px]">{text}</div>
          {/* <a className="text-[12px] !text-[#0071FF]" onClick={() => jumpOrchestration(record)}>
            查看详情
          </a> */}
        </div>
      ),
      width: 200,
    },
    {
      title: '应用类型',
      dataIndex: 'app_type',
      key: 'app_type',
      render: (value) => <span>{getAppType(value)}</span>,
      width: 200,
    },
    {
      title: '应用描述',
      dataIndex: 'app_description',
      width: 200,
    },
    {
      title: '创建人',
      dataIndex: 'user_name',
      render: (_, record) => (
        <span>
          {record.group_name}
          {record.group_name || record.user_name ? ' / ' : ''}
          {record.user_name}
        </span>
      ),
      width: 200,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (value) => <span>{formatData(value)}</span>,
      width: 200,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div className="flex">
          <a
            className="flex items-center !text-@brand-color"
            onClick={() => jumpOrchestration(record)}
          >
            <SvgIcon icon="message-ic1" size="20" className="mr-1" />
            查看
          </a>
          <a
            className="ml-8 flex items-center !text-@brand-color"
            onClick={() => handlePassed(record)}
          >
            <SvgIcon icon="message-ic4" size="15" className="mr-1" />
            通过
          </a>
          <a
            className="ml-8 flex items-center !text-@error-color"
            onClick={() => handleModalOpen(record)}
          >
            <SvgIcon icon="message-ic5" size="15" className="mr-1" />
            驳回
          </a>
        </div>
      ),
      width: 200,
    },
  ];

  const columnsHistor: TableProps<GetReviewAppList>['columns'] = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text) => (
        <div>
          <div className="w-[200px] overflow-hidden overflow-ellipsis whitespace-nowrap text-[16px]">
            {text}
          </div>
          {/* {record.is_visible ? (
            <a className="text-[12px] !text-@brand-color" onClick={() => jumpOrchestration(record)}>
              查看详情
            </a>
          ) : (
            <div className="text-[12px] text-@error-color">应用已被删除无法查看</div>
          )} */}
        </div>
      ),
    },
    {
      title: '应用类型',
      dataIndex: 'app_type',
      key: 'app_type',
      render: (value) => <span>{getAppType(value)}</span>,
      width: 150,
    },
    {
      title: '应用描述',
      dataIndex: 'app_description',
      width: 250,
      render: (value) => (
        <div className="w-[300px] overflow-hidden overflow-ellipsis whitespace-nowrap">{value}</div>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'user_name',
      width: 200,
      render: (_, record) => (
        <div className="w-[200px] overflow-hidden overflow-ellipsis whitespace-nowrap">
          {record.group_name}
          {record.group_name || record.user_name ? ' / ' : ''}
          {record.user_name}
        </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (value) => <span>{formatData(value)}</span>,
      width: 200,
    },
    {
      title: '审批结果',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <div
          className={`flex w-[68px] items-center justify-center rounded p-1 text-[14px] ${
            record.review_result === 'pass'
              ? 'bg-[#F0F8FF] text-@brand-color'
              : 'bg-[#FFF1F0] text-@error-color'
          }`}
        >
          <SvgIcon
            icon={record.review_result === 'pass' ? 'message-ic4' : 'message-ic5'}
            size="15"
            className="mr-1"
          />
          {record.review_result === 'pass' ? '通过' : '驳回'}
        </div>
      ),
    },
    {
      title: '审批时间',
      dataIndex: 'review_time',
      key: 'review_time',
      width: 200,
      render: (value) => <span>{formatData(value)}</span>,
    },
    {
      title: '审批意见',
      key: 'action',
      width: 250,
      render: (_, record) => {
        // 使用行级展开状态
        const isExpanded = expandedRows[record.app_id] || false;

        return (
          <>
            <div
              className={`${
                !isExpanded ? 'line-clamp-2' : ''
              } w-[200px] overflow-hidden text-ellipsis`}
            >
              <div
                ref={(el) => {
                  contentRefs.current[record.app_id] = el;
                }}
                className="text-sm text-[#292D32]"
              >
                {record.review_description}
              </div>
            </div>
            {overflowRowMap[record.app_id] && (
              <div className="cursor-pointer">
                {!isExpanded ? (
                  <div
                    className="flex items-center text-sm text-[#1B6DFA]"
                    onClick={() => toggleRowExpansion(record.app_id)}
                  >
                    <DownOutlined />
                    展开
                  </div>
                ) : (
                  <div
                    className="flex items-center text-sm text-[#1B6DFA]"
                    onClick={() => toggleRowExpansion(record.app_id)}
                  >
                    <UpOutlined />
                    收起
                  </div>
                )}
              </div>
            )}
          </>
        );
      },
    },
  ];

  // 根据渲染结果检测“审批意见”是否超过两行
  useEffect(() => {
    const map: Record<string, boolean> = {};
    tablesData.forEach((item) => {
      const el = contentRefs.current[item.app_id as string];
      if (el) {
        const style = window.getComputedStyle(el);
        const lineHeightPx = style.lineHeight;
        let lineHeight = 0;
        if (lineHeightPx.endsWith('px')) {
          lineHeight = parseFloat(lineHeightPx);
        } else {
          const fontSize = parseFloat(style.fontSize || '14');
          lineHeight = fontSize * 1.2;
        }
        const maxTwoLinesHeight = lineHeight * 2 + 1;
        map[item.app_id as string] = el.scrollHeight > maxTwoLinesHeight;
      }
    });
    setOverflowRowMap(map);
  }, [tablesData, containerSize?.width]);

  /**
   * @description: 审核通过
   * @return {*}
   */
  const handlePassed = (value: GetReviewAppList) => {
    appService
      .reviewApp(value.app_id, {
        review_result: 'pass',
        review_description: '',
      })
      .then((res) => {
        if (res.reviewer) {
          setTipsValue(res);
          modal.review.open();
          return;
        }
        setTablesData(tablesData.filter((item) => item.app_id !== value.app_id));
        message.success('审核通过');
      });
  };

  /**
   * @description: 开启弹窗
   * @return {*}
   */
  const handleModalOpen = (value: GetReviewAppList) => {
    setDefaultDismiss(value);
    modal.dismiss.open();
  };

  /**
   * @description: 点击确定弹窗
   * @return {*}
   */
  const handleModalOk = () => {
    if (dismiss.trim().length === 0) {
      message.error('请填写驳回原因');
      return;
    }
    modal.dismiss.startLoading();
    appService
      .reviewApp(defaultDismiss?.app_id as string, {
        review_result: 'reject',
        review_description: dismiss,
      })
      .then((res) => {
        if (res.reviewer) {
          setTipsValue(res);
          modal.review.open();
          return;
        }
        setTablesData(tablesData.filter((item) => item.app_id !== defaultDismiss?.app_id));
        message.warning('审批已驳回!');
        setDismiss('');
        modal.dismiss.close();
      })
      .finally(() => {
        modal.dismiss.stopLoading();
      });
  };

  const handlePagination = (page: number, pageSize: number) => {
    setPagingInfo({ ...pagingInfo, page: page, page_size: pageSize });
  };

  const handleSearch = (value: string) => {
    setPagingInfo({ ...pagingInfo, page: 1, searchText: value });
  };

  const handleSearchFn = debounce(handleSearch, 500);

  return (
    <div ref={containerRef} className="flex h-full flex-col">
      {/* <div className="h-full max-h-full"> */}
      <PagesHeader>
        应用审批
        <TipDesc title="用于管理员或指定审批人对新创建的智能体应用进行审核和发布管理" />
      </PagesHeader>
      <div
        // className="mt-[18px] h-full rounded-default"
        className=" flex flex-1 flex-col rounded-default bg-[#FFF] px-5"
        // style={{
        //   background:
        //     'linear-gradient(180deg, rgba(251, 252, 255, 0.5) 0%, rgba(255, 255, 255, 0.5) 59.81%)',
        // }}
      >
        <div
          className=" "
          // style={{
          //   padding: '12px 28px 0 14px',
          // }}
        >
          <Tabs defaultActiveKey={key} items={items} onChange={onChange} />
          {/* <Input
            placeholder="搜索"
            prefix={<SearchOutlined />}
            style={{
              height: '32px',
              width: '200px',
            }}
            onChange={(e) => handleSearchFn(e.target?.value)}
          /> */}
          <Input
            onChange={(e) => handleSearchFn(e.target?.value)}
            className="mb-[16px] !rounded-md"
            style={{
              height: '32px',
              width: '240px',
            }}
            placeholder="搜索"
            suffix={<SvgIcon icon="work-ic6" size={16} />}
          />
        </div>

        {tablesData.length > 0 ? (
          <div className="h-full flex-1 rounded-default  text-[#292D32]">
            {/* <div className="h-full flex-1 rounded-default px-[6px] text-[#292D32]" ref={tableRef}> */}
            <Tables<GetReviewAppList>
              rowBgClassName="bg-[#FFF]"
              columns={tabsValue === '1' ? columnsReview : columnsHistor}
              dataSource={tablesData}
              pagination={false}
              rowKey={'index'}
              paginationProps={{
                pageSize: pagingInfo.page_size,
                current: pagingInfo.page,
                total: pagingTotal,
                onChange: handlePagination,
              }}
            />

            {/* <div className="pb-[14px]">
              <Pagination
                showQuickJumper
                showSizeChanger
                current={pagingInfo.page}
                pageSize={pagingInfo.page_size}
                total={pagingTotal}
                align="end"
                onChange={handlePagination}
              />
            </div> */}
          </div>
        ) : (
          <NotData />
        )}
      </div>

      <Modals
        title="驳回原因"
        open={modal.dismiss.isOpen}
        onOk={handleModalOk}
        onCancel={() => {
          modal.dismiss.close();
          setDismiss('');
        }}
        confirmLoading={modal.dismiss.isLoading}
      >
        <TextArea
          placeholder="请输入驳回原因"
          autoSize={{ minRows: 10, maxRows: 10 }}
          showCount
          maxLength={LONG_TEXT}
          value={dismiss}
          onChange={(e) => setDismiss(e.target.value)}
          bg
        />
      </Modals>

      <Modals
        title={`该应用已${tipsValue?.review_description !== undefined ? '通过' : '驳回'}`}
        open={modal.review.isOpen}
        footerCancelHidden={false}
        okText="知道了"
        closable={false}
        onOk={modal.review.close}
      >
        <div>审批人:{tipsValue?.reviewer}</div>
        <div>审批时间:{formatData(tipsValue?.update_time ? tipsValue?.update_time : '')}</div>
        {tipsValue?.review_description !== undefined && (
          <div>驳回原因:{tipsValue?.review_description}</div>
        )}
      </Modals>
    </div>
  );
};

export default AppReview;
